import { router } from '@/router/router.js'
import store from '@/store'
import { getToken, setToken } from '@/utils/auth'

// setToken('eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjQ3YTBkZjFhLTEwOGItNGQ3OC04YmE1LTgxMWY5YmU0ODI3YyJ9.qr03CATJUJ5CTNkVh0pTP3eIf9BNZx85YJUV7dQR8s440TgYabjJeMq0ZZ4mchkJpfbbhdV0R-J1RGZ7NYapiQ')

// no redirect whitelist
// 白名单
const whiteList = ['/login']

router.beforeEach(async(to, from, next) => {
  // set page title
  document.title = to.meta.title

  // determine whether the user has logged in
  const hasToken = getToken()

  // 白名单
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  if (!hasToken) {
    next('/login')
    return
  }

  // 有用户数据 ,直接访问页面
  if (store.state.user.userId) {
    next()
    return
  }

  // 没有用户数据, 有token
  if (hasToken) {
    await store.dispatch('user/getInfo')

    // 初始微信功能
    await store.dispatch('user/wxConfig')
    next()
    return
  }
  next()
})

router.afterEach(() => {
  // finish progress bar
})
